package cn.flant.io.tools;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import cn.flant.io.IOUtil;

public class UdpConnector extends Connector {

	private DatagramSocket socket = null;
	private InetAddress inetAddress;
	private boolean isConnected = false;

	public UdpConnector(String host, int port) {
		super(host, port);
	}

	public UdpConnector(String host, int port, boolean enableCache) {
		super(host, port, enableCache);
	}

	@Override
	protected void closeConnection() {
		isConnected = false;
		IOUtil.close(socket);
		socket = null;
		inetAddress = null;
	}

	@Override
	public boolean isConnected() {
		return isConnected;
	}

	@Override
	protected boolean openConnection() {
		if (isConnected) {
			return true;
		}
		try {
			inetAddress = InetAddress.getByName(host);
			socket = new DatagramSocket();
			isConnected = true;
			return true;
		} catch (Exception e) {
			log.error("create DatagramSocket failed: " + e.getMessage());
			closeConnection();
		}
		return false;
	}

	@Override
	protected boolean sendData(byte[] bytes) {
		if (bytes == null) {
			return false;
		}
		try {
			DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inetAddress, port);
			socket.send(packet);
		} catch (Exception e) {
			log.error("send data failed: " + e.getMessage());
			closeConnection();
		}
		return true;
	}
}
